﻿using System;
using System.Collections.Generic;
using System.Linq;
using Norm;
using Norm.BSON.DbTypes;

// http://wiki.github.com/atheken/NoRM/
class Example1 {

    public Example1() {
        var connectionUrl = "mongodb://localhost/NormExamples";

        // Opening a database connection.
        using (var db = Mongo.Create(connectionUrl)) {
            //db.Database.DropCollection("Product");
            //db.Database.DropCollection("Brand");
            var prodCollection = db.GetCollection<Product>();
            var brandCollection = db.GetCollection<Brand>();

            // Constructing complex documents and saving.
            var places = new List<Address>();
            foreach (int index in Enumerable.Range(0, 6)) {
                places.Add(new Address { StreetName = String.Format("#{0}, Street St", index) });
            }

            var acme = new Brand { Name = "Acme Inc.", CustomerRating = 8 };
            acme.Suppliers.Add(places[0]);
            acme.Suppliers.Add(places[1]);
            brandCollection.Save(acme);

            var apple = new Brand { Name = "Apple, Inc.", CustomerRating = 7 };
            apple.Suppliers.Add(new Address { StreetName = "Infinite Loop" });
            brandCollection.Save(apple);

            // Creating database references.
            var rocketBoots = new Product { Price = 100, Shipping = places[4], Name = "Rocket Boots" };
            rocketBoots.TheBrand = new DbReference<Brand>(acme._id);
            prodCollection.Save(rocketBoots);

            var explosives = new Product { Price = 10, Shipping = places[2], Name = "Explosives" };
            explosives.TheBrand = new DbReference<Brand>(acme._id);

            var iPod = new Product { Price = 350, Shipping = places[5], Name = "iPod Mini" };
            iPod.TheBrand = new DbReference<Brand>(apple._id);
            prodCollection.Save(iPod);
        }

        // Reading data and DB References.
        using (var db = Mongo.Create(connectionUrl)) {
            var prodCollection = db.GetCollection<Product>();
            var brandCollection = db.GetCollection<Brand>();

            foreach (var product in prodCollection.AsQueryable().ToList()) {
                var theBrand = product.TheBrand.Fetch(() => db);
                Console.WriteLine("Available: {0} {1}", product.ToString(), theBrand.ToString());
            }

            var results = prodCollection.AsQueryable().Where(p => p.Price > 300)
                .Select(p => new { p.Price, p._id }).ToArray();
            foreach (var product in results) {
                Console.WriteLine(product.ToString());
            }

            var result = prodCollection.AsQueryable().Where(p => p.Price > 300)
                .Select(p => new { p.Price, p._id }).First();
            Console.WriteLine(result.ToString());
        }
    }

}
